<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">


<meta name="google-site-verification" content="E9deYnivN5MuHMuIfiMZZfS0alv-d_0UjcwjBL79lGU" />



<meta name="baidu-site-verification" content="iHYWJxscwD" />










<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />



  <meta name="google-site-verification" content="true" />








  <meta name="baidu-site-verification" content="true" />







  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="python,量化投资,股价预测,多元线性回归," />










<meta name="description" content="又想了一个问题:预测股价。这回跟量化有直接关系了吧？先看两篇文章首先是一篇综述性文章。徐程成.股票价格预测方法综述.中国市场,2020, (9):42-43,68.股票预测的方法有:1.传统方法:①基于统计学和概率论的VAR(向量自回归模型)、ARM(自回归滑动平均模型)、指数平滑模型。②基于非统计原理的GM、SVM以及ANN创新型预测模型。③灰色预测法。④人工神经网络。2.集合经验模态分解方法(">
<meta property="og:type" content="article">
<meta property="og:title" content="量化投资学习笔记103——股价预测1:总体规划及数据获取">
<meta property="og:url" content="https://zwdnet.github.io/2021/03/23/%E9%87%8F%E5%8C%96%E6%8A%95%E8%B5%84%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0103%E2%80%94%E2%80%94%E8%82%A1%E4%BB%B7%E9%A2%84%E6%B5%8B1-%E6%80%BB%E4%BD%93%E8%A7%84%E5%88%92%E5%8F%8A%E6%95%B0%E6%8D%AE%E8%8E%B7%E5%8F%96/index.html">
<meta property="og:site_name" content="赵瑜敏的口腔医学专业学习博客">
<meta property="og:description" content="又想了一个问题:预测股价。这回跟量化有直接关系了吧？先看两篇文章首先是一篇综述性文章。徐程成.股票价格预测方法综述.中国市场,2020, (9):42-43,68.股票预测的方法有:1.传统方法:①基于统计学和概率论的VAR(向量自回归模型)、ARM(自回归滑动平均模型)、指数平滑模型。②基于非统计原理的GM、SVM以及ANN创新型预测模型。③灰色预测法。④人工神经网络。2.集合经验模态分解方法(">
<meta property="og:locale">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/74/01.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/74/02.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/74/03.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/74/04.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/74/05.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/74/06.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/74/07.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/74/08.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/wx.jpg">
<meta property="article:published_time" content="2021-03-23T06:57:28.000Z">
<meta property="article:modified_time" content="2021-03-25T07:41:46.125Z">
<meta property="article:author" content="赵瑜敏">
<meta property="article:tag" content="python">
<meta property="article:tag" content="量化投资">
<meta property="article:tag" content="股价预测">
<meta property="article:tag" content="多元线性回归">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/74/01.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://zwdnet.github.io/2021/03/23/量化投资学习笔记103——股价预测1-总体规划及数据获取/"/>





  <title>量化投资学习笔记103——股价预测1:总体规划及数据获取 | 赵瑜敏的口腔医学专业学习博客</title>
  








<meta name="generator" content="Hexo 5.4.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">赵瑜敏的口腔医学专业学习博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/%20" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/%20" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/%20" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/%20" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://zwdnet.github.io/2021/03/23/%E9%87%8F%E5%8C%96%E6%8A%95%E8%B5%84%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0103%E2%80%94%E2%80%94%E8%82%A1%E4%BB%B7%E9%A2%84%E6%B5%8B1-%E6%80%BB%E4%BD%93%E8%A7%84%E5%88%92%E5%8F%8A%E6%95%B0%E6%8D%AE%E8%8E%B7%E5%8F%96/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/tx.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="赵瑜敏的口腔医学专业学习博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">量化投资学习笔记103——股价预测1:总体规划及数据获取</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2021-03-23T06:57:28+00:00">
                2021-03-23
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E9%87%8F%E5%8C%96%E6%8A%95%E8%B5%84/" itemprop="url" rel="index">
                    <span itemprop="name">量化投资</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                  <span class="post-meta-divider">|</span>
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  1.9k
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  8
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>又想了一个问题:预测股价。这回跟量化有直接关系了吧？<br>先看两篇文章<br>首先是一篇综述性文章。<br>徐程成.股票价格预测方法综述.中国市场,2020, (9):42-43,68.<br>股票预测的方法有:<br>1.传统方法:<br>①基于统计学和概率论的VAR(向量自回归模型)、ARM(自回归滑动平均模型)、指数平滑模型。<br>②基于非统计原理的GM、SVM以及ANN创新型预测模型。<br>③灰色预测法。<br>④人工神经网络。<br>2.集合经验模态分解方法(EEMD)<br>3.机器学习方法:多种机器学习方法与金融模型融合。<br>4.时间序列方法:ARMA,ARIMA,GARCH等，以及与小波分析等方法结合。<br>5.神经网络:BP神经网络，小波神经网络，遗传算法等。<br>再来看具体的预测方法。<br>一篇用简单的多元线性回归模型进行预测的:<br>王培冬.基于多元线性回归的股价分析及预测.科技经济市场，2020(1):84-85.<br>此文用多元线性回归模型对沪深300指数进行了预测，以开盘价，收盘价，最高价，最低价，成交量，成交额，次日开盘价为自变量，以第二天收盘价为预测目标，用多元线性回归模型进行预测。我先用python尝试实现一下吧。<br>首先要搞到数据。开始用tushare，这个我从一开始就用了，发现提示要升级到pro版了，要使用更多功能要去挣积分，关键是积分有效期一年……我尝试了一下，好麻烦。收费我绝对不反对，但不应该这么折腾初级用户。想到了我以前用的一个笔记软件——为知笔记。它开始收费我就换到印象笔记了，尽管免费版基本够用了，我还是买了高级账户。扯远了，回来。找到个替代品:akshare。<a target="_blank" rel="noopener" href="https://www.akshare.xyz/zh_CN/latest/">官网</a><br>选取沪深300指数2018年一整年的数据进行预测分析。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> tushare <span class="keyword">as</span> ts</span><br><span class="line"><span class="keyword">import</span> akshare <span class="keyword">as</span> ak</span><br><span class="line"><span class="keyword">import</span> pandas <span class="keyword">as</span> pd</span><br><span class="line"><span class="keyword">import</span> os</span><br><span class="line"><span class="keyword">import</span> run</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 下载历史数据，用akshare</span></span><br><span class="line"><span class="meta">@run.change_dir</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">downloadData</span>(<span class="params">code=<span class="string">&quot;sh000300&quot;</span></span>):</span></span><br><span class="line">    result = ak.stock_zh_index_daily_em(symbol=code)</span><br><span class="line">    result.index = result.date</span><br><span class="line">    result = result.loc[:, [<span class="string">&quot;open&quot;</span>, <span class="string">&quot;close&quot;</span>, <span class="string">&quot;high&quot;</span>, <span class="string">&quot;low&quot;</span>, <span class="string">&quot;volume&quot;</span>, <span class="string">&quot;amount&quot;</span>]]</span><br><span class="line">    <span class="comment"># print(result)</span></span><br><span class="line">    result.to_csv(<span class="string">&quot;./result.csv&quot;</span>)</span><br><span class="line">    </span><br><span class="line">    </span><br><span class="line"><span class="comment"># 从文件读取数据</span></span><br><span class="line"><span class="meta">@run.change_dir</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">loadData</span>(<span class="params">code=<span class="string">&quot;sh000300&quot;</span>, start=<span class="string">&quot;2018-01-01&quot;</span>, end=<span class="string">&quot;2018-12-31&quot;</span>, refresh = <span class="literal">False</span></span>):</span></span><br><span class="line">    datafile = <span class="string">&quot;./result.csv&quot;</span></span><br><span class="line">    <span class="keyword">if</span> os.path.exists(datafile) == <span class="literal">False</span> <span class="keyword">or</span> refresh == <span class="literal">True</span>:</span><br><span class="line">        downloadData(code)</span><br><span class="line">    data = pd.read_csv(<span class="string">&quot;./result.csv&quot;</span>, index_col=<span class="string">&quot;date&quot;</span>)</span><br><span class="line">    data = data[start : end]</span><br><span class="line">    <span class="comment"># print(data.describe())</span></span><br><span class="line">    <span class="keyword">return</span> data</span><br></pre></td></tr></table></figure>
<p>接着对数据进行处理，生成特征和目标值。次日收盘价为目标值。<br>就用多元线性回归模型对次交易日指数进行预测。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 数据预处理</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">preProcess</span>(<span class="params">data</span>):</span></span><br><span class="line">    data[<span class="string">&quot;nextclose&quot;</span>] = data[<span class="string">&quot;close&quot;</span>].shift(-<span class="number">1</span>)</span><br><span class="line">    data[<span class="string">&quot;nextopen&quot;</span>] = data[<span class="string">&quot;open&quot;</span>].shift(-<span class="number">1</span>)</span><br><span class="line">    result = data.iloc[:-<span class="number">1</span>, :]</span><br><span class="line">    print(<span class="built_in">len</span>(result))</span><br><span class="line">    <span class="keyword">return</span> result</span><br></pre></td></tr></table></figure>
<p>OK，可以开始干活了。<br>加载完数据，画箱状图看看。<br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/74/01.png"></p>
<p>成交量数据远远大于其它数据，做标准化吧。<br>做完再画图看看。(标化以后又乘500再加了3500)<br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/74/02.png"></p>
<p>画配对图看看<br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/74/03.png"></p>
<p>OK，开始正式干活吧。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 训练</span></span><br><span class="line">model = LinearRegression()</span><br><span class="line">model.fit(X_train, Y_train)</span><br><span class="line">a = model.intercept_</span><br><span class="line">b = model.coef_</span><br><span class="line">print(<span class="string">&quot;截距:&quot;</span>, a)</span><br><span class="line">print(<span class="string">&quot;回归系数:&quot;</span>, b)</span><br></pre></td></tr></table></figure>
<p>结果<br>截距: [2.36916081]                                              回归系数: [[-0.15301665  0.17758906  0.25901863 -0.39743459 -0.02732929  1.09816001 0.04366043]]<br>模型评分: 0.9880317755151593<br>论文给出的R²评分为0.989或0.988，我的结果与其很接近的。<br>下面输出残差对预测值的散点图。<br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/74/04.png"></p>
<p>随机分布，无任何规律性，说明数据满足模型基本假设。<br>下面应用模型，载入2019年的数据，用模型进行预测看看。<br>模型验证评分: 0.976653552728345<br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/74/05.png"></p>
<p>验证结果，大的趋势还是蛮像的，但是短期会有很大偏离。而我们使用今天的数据(以及明天开盘的数据)预测明天收盘，所以这种预测并没有啥卵用……<br>再看看预测误差<br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/74/06.png"></p>
<p>画直方图看看。<br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/74/07.png"></p>
<p>基本还是正态分布的。平均误差率-0.15%。<br>现在，来重构一下整个程序，把重复的部分提取出来。<br>最后，用一个策略来实际检验一下模型吧:从第二个交易日开始，用模型对当天的收盘价进行预测，并与头一天对比，如果上涨则以开盘价全仓(前一天资金的90%，因为还要cover手续费)买入，如果下跌则以开盘价清仓。当然这个策略不太真实，我不可能以开盘价买入，而且买入那么多。<br>这是用2019年整年的数据回测的结果。<br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/74/08.png"></p>
<p>可以说相当好了，一年涨了3倍。下面计算各种回测指标。用empyrical库计算，建了一个回测类。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> empyrical <span class="keyword">as</span> ey</span><br><span class="line"><span class="keyword">import</span> math</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 策略回测类</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">BackTest</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span>(<span class="params">self, model, code=<span class="string">&quot;sh000300&quot;</span>, start=<span class="string">&quot;2019-01-01&quot;</span>, end=<span class="string">&quot;2019-12-31&quot;</span></span>):</span></span><br><span class="line">        self.data = loadData(code=code, start=start, end=end)</span><br><span class="line">        self.X, self.Y = splitData(self.data)</span><br><span class="line">        self.model = model             <span class="comment"># 模型</span></span><br><span class="line">        self.stock = [<span class="number">0</span>]                     <span class="comment"># 持仓</span></span><br><span class="line">        self.cash = [<span class="number">100000000</span>]    <span class="comment"># 现金</span></span><br><span class="line">        self.value = []                        <span class="comment"># 资产总额</span></span><br><span class="line">        self.cost = [<span class="number">0.0</span>]                    <span class="comment"># 交易成本</span></span><br><span class="line">        self.fee_rate = <span class="number">1e-4</span>              <span class="comment"># 手续费率</span></span><br><span class="line">        self.modelname = <span class="built_in">str</span>(model)[:-<span class="number">2</span>] <span class="comment"># 模型名称</span></span><br><span class="line">        self.bk_results = pd.DataFrame()</span><br><span class="line">        </span><br><span class="line">    <span class="comment"># 进行回测</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">run</span>(<span class="params">self</span>):</span></span><br><span class="line">        <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="built_in">len</span>(self.data)):</span><br><span class="line">            today_X = self.X.iloc[i, :]</span><br><span class="line">            pred_Y = self.model.predict(today_X.values.reshape(<span class="number">1</span>, -<span class="number">1</span>))</span><br><span class="line">            <span class="keyword">if</span> i == <span class="number">0</span>:</span><br><span class="line">                <span class="comment"># print(&quot;第0天&quot;)</span></span><br><span class="line">                amount = <span class="number">0</span></span><br><span class="line">            <span class="keyword">elif</span> pred_Y[<span class="number">0</span>][<span class="number">0</span>] &gt; today_X.<span class="built_in">open</span>: <span class="comment"># 全仓买入</span></span><br><span class="line">                <span class="comment"># print(&quot;买&quot;)</span></span><br><span class="line">                money = self.cash[i - <span class="number">1</span>]</span><br><span class="line">                price = today_X.<span class="built_in">open</span></span><br><span class="line">                amount = math.floor(<span class="number">0.9</span>*money/price)</span><br><span class="line">                <span class="comment"># 买入操作</span></span><br><span class="line">                self.stock.append(self.stock[i-<span class="number">1</span>] + amount)</span><br><span class="line">                self.cash.append(money - price*amount*(<span class="number">1.0</span> + self.fee_rate))</span><br><span class="line">                self.cost.append(self.cost[i-<span class="number">1</span>] + price*amount*self.fee_rate)</span><br><span class="line">            <span class="keyword">elif</span> pred_Y[<span class="number">0</span>][<span class="number">0</span>] &lt;= today_X.<span class="built_in">open</span>: <span class="comment"># 清仓</span></span><br><span class="line">                <span class="comment"># print(&quot;卖&quot;)</span></span><br><span class="line">                amount = self.stock[i-<span class="number">1</span>]</span><br><span class="line">                price = today_X.<span class="built_in">open</span></span><br><span class="line">                self.stock.append(<span class="number">0</span>)</span><br><span class="line">                money = amount*price</span><br><span class="line">                self.cash.append(money*(<span class="number">1.0</span> - self.fee_rate) + self.cash[i-<span class="number">1</span>])</span><br><span class="line">                self.cost.append(self.cost[i-<span class="number">1</span>] + money*self.fee_rate)</span><br><span class="line">            self.value.append(self.cash[i] + self.stock[i]*today_X.close)</span><br><span class="line">            </span><br><span class="line">        <span class="comment"># 生成收益率数据</span></span><br><span class="line">        self.genReturn()</span><br><span class="line">        </span><br><span class="line">        <span class="comment"># 计算回测指标</span></span><br><span class="line">        self.evaluation()</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">return</span> self.bk_results</span><br><span class="line">            </span><br><span class="line">    <span class="comment"># 生成收益率数据</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">genReturn</span>(<span class="params">self</span>):</span></span><br><span class="line">        <span class="comment"># 生成收益率数据</span></span><br><span class="line">        self.return_value = pd.DataFrame(self.value)</span><br><span class="line">        self.return_value[<span class="string">&quot;value&quot;</span>] = self.value</span><br><span class="line">        self.return_value[<span class="string">&quot;returns&quot;</span>] = self.return_value[<span class="string">&quot;value&quot;</span>].pct_change()</span><br><span class="line">        self.return_value[<span class="string">&quot;benchmark_returns&quot;</span>] = self.data[<span class="string">&quot;close&quot;</span>].pct_change().values</span><br><span class="line">        self.return_value[<span class="string">&quot;date&quot;</span>] = self.data.index[:<span class="built_in">len</span>(self.value)]</span><br><span class="line">        self.return_value.index = self.return_value[<span class="string">&quot;date&quot;</span>]</span><br><span class="line">            </span><br><span class="line">    <span class="comment"># 画结果</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">draw</span>(<span class="params">self</span>):</span></span><br><span class="line">        oldpath = os.getcwd()</span><br><span class="line">        newpath = <span class="string">&quot;/home/code/&quot;</span></span><br><span class="line">        os.chdir(newpath)</span><br><span class="line">        plt.figure()</span><br><span class="line">        plt.plot(self.value)</span><br><span class="line">        plt.savefig(<span class="string">&quot;./output/&quot;</span> + modelname + <span class="string">&quot;_backtest_value.png&quot;</span>)</span><br><span class="line">        plt.close()</span><br><span class="line">        <span class="comment"># 画每日收益率图</span></span><br><span class="line">        plt.figure()</span><br><span class="line">        plt.plot(self.return_value[<span class="string">&quot;returns&quot;</span>])</span><br><span class="line">        plt.savefig(<span class="string">&quot;./output/&quot;</span> + modelname + <span class="string">&quot;_backtest_returns.png&quot;</span>)</span><br><span class="line">        plt.close()</span><br><span class="line">        os.chdir(oldpath)</span><br><span class="line">        </span><br><span class="line">    <span class="comment"># 计算并返回回测评估结果</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">evaluation</span>(<span class="params">self</span>):</span></span><br><span class="line">        returns = self.return_value.returns</span><br><span class="line">        benchmark = self.return_value.benchmark_returns</span><br><span class="line">        excess_return = returns - benchmark</span><br><span class="line">    </span><br><span class="line">        <span class="comment"># 用empyrical计算回测指标</span></span><br><span class="line">        <span class="comment"># 年化收益率</span></span><br><span class="line">        self.bk_results[<span class="string">&quot;年化收益率&quot;</span>] = [ey.annual_return(returns)]</span><br><span class="line">        <span class="comment"># 累计收益率</span></span><br><span class="line">        self.bk_results[<span class="string">&quot;累计收益率&quot;</span>] = [ey.cum_returns(returns)]</span><br><span class="line">        <span class="comment"># 最大回撤</span></span><br><span class="line">        self.bk_results[<span class="string">&quot;最大回撤&quot;</span>] = [ey.max_drawdown(returns)]</span><br><span class="line">        <span class="comment"># 夏普比率</span></span><br><span class="line">        self.bk_results[<span class="string">&quot;夏普比率&quot;</span>] = [ey.sharpe_ratio(excess_return)]</span><br><span class="line">        <span class="comment"># 索提比率</span></span><br><span class="line">        self.bk_results[<span class="string">&quot;索提比率&quot;</span>] = [ey.sortino_ratio(returns)]</span><br><span class="line">        <span class="comment"># αβ值</span></span><br><span class="line">        ab = ey.alpha_beta(returns, benchmark, risk_free = <span class="number">0.02</span>)</span><br><span class="line">        self.bk_results[<span class="string">&quot;α&quot;</span>] = ab[<span class="number">0</span>]</span><br><span class="line">        self.bk_results[<span class="string">&quot;β&quot;</span>] = ab[<span class="number">1</span>]</span><br></pre></td></tr></table></figure>
<p>回测结果:<br>最大回撤 -0.014615<br>夏普比率 6.859218<br>索提比率 49.698812<br>α -0.729592<br>β 0.5453<br>好不好呢？不好评价，看看其它方法吧。<br><a target="_blank" rel="noopener" href="https://github.com/zwdnet/stock">源代码</a></p>
<p>我发文章的三个地方，欢迎大家在朋友圈等地方分享，欢迎点“在看”。<br>我的个人博客地址：<a href="https://zwdnet.github.io/">https://zwdnet.github.io</a><br>我的知乎文章地址： <a target="_blank" rel="noopener" href="https://www.zhihu.com/people/zhao-you-min/posts">https://www.zhihu.com/people/zhao-you-min/posts</a><br>我的微信个人订阅号：赵瑜敏的口腔医学学习园地</p>
<p><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/wx.jpg"></p>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>欢迎打赏！感谢支持！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/mm_facetoface_collect_qrcode_1542944836634.png" alt=" 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/1542944857770.jpg" alt=" 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/python/" rel="tag"># python</a>
          
            <a href="/tags/%E9%87%8F%E5%8C%96%E6%8A%95%E8%B5%84/" rel="tag"># 量化投资</a>
          
            <a href="/tags/%E8%82%A1%E4%BB%B7%E9%A2%84%E6%B5%8B/" rel="tag"># 股价预测</a>
          
            <a href="/tags/%E5%A4%9A%E5%85%83%E7%BA%BF%E6%80%A7%E5%9B%9E%E5%BD%92/" rel="tag"># 多元线性回归</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2021/03/16/%E5%AD%A6%E4%B9%A0%E5%A4%B4%E5%BD%B1%E6%B5%8B%E9%87%8F1%E2%80%94%E2%80%94%E8%A7%A3%E5%89%96%E7%BB%93%E6%9E%84%E6%8F%8F%E8%AE%B0%E5%9B%BE/" rel="next" title="学习头影测量1——解剖结构描记图">
                <i class="fa fa-chevron-left"></i> 学习头影测量1——解剖结构描记图
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2021/03/27/%E5%AD%A6%E4%B9%A0%E5%A4%B4%E5%BD%B1%E6%B5%8B%E9%87%8F2%E2%80%94%E2%80%94%E6%8F%8F%E8%BF%B9%E6%96%B9%E6%B3%95%E5%8F%8A%E6%A0%87%E5%BF%97%E7%82%B9%E5%AE%9A%E7%82%B9%E3%80%82/" rel="prev" title="学习头影测量2——描迹方法及标志点定点。">
                学习头影测量2——描迹方法及标志点定点。 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC80MTA2Mi8xNzU4Nw=="></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/tx.jpg"
                alt="" />
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/%20%7C%7C%20archive">
              
                  <span class="site-state-item-count">452</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">29</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">544</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">本站版权归赵瑜敏所有，如欲转载请与本人联系。</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">1225.8k</span>
  
</div>









<div>
  <script type="text/javascript">var cnzz_protocol = (("https:" == document.location.protocol) ? " https://" : " http://");document.write(unescape("%3Cspan id='cnzz_stat_icon_1275447216'%3E%3C/span%3E%3Cscript src='" + cnzz_protocol + "s11.cnzz.com/z_stat.php%3Fid%3D1275447216%26online%3D1%26show%3Dline' type='text/javascript'%3E%3C/script%3E"));</script>
</div>

        







  <div style="display: none;">
    <script src="//s95.cnzz.com/z_stat.php?id=1275447216&web_id=1275447216" language="JavaScript"></script>
  </div>



        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  












  





  

  

  

  
  

  

  

  

  
</body>
</html>
